// const information = document.getElementById('info')
// information.innerText = `This app is using Chrome (v${versions.chrome()}), Node.js (v${versions.node()}), and Electron (v${versions.electron()})`
// renderer.js
const startButton = document.getElementById("startButton");
const stopButton = document.getElementById("stopButton");
const video = document.querySelector("video");
let pcMap = new Map();
let screenStream;
let ws;
async function getMessageData(msg) {
  let message = "";
  if (msg.data instanceof Blob) {
    const str = await new Response(msg.data).text();
    message = JSON.parse(str);
  } else {
    message = JSON.parse(msg.data);
  }
  return message;
}
// 接收端中途加入,创建新的连接;因为webRTC是点对点协议
function createNewPc(ws, to) {
  console.log("screenStream", screenStream);
  if (!screenStream) {
    console.log("没有检测到共享屏幕");
    return;
  }
  let newpc = new RTCPeerConnection();
  screenStream
    .getTracks()
    .forEach((track) => newpc.addTrack(track, screenStream));
  newpc.onicecandidate = (e) => {
    if (e.candidate) {
      ws.send(JSON.stringify({ type: "candidate", data: e.candidate, to }));
    }
  };
  return newpc;
}
// 手动结束屏幕共享
function stopSharing() {
  ws.send(JSON.stringify({ type: "close" }));
  if (screenStream) {
    screenStream.getTracks().forEach((track) => track.stop());
    console.log("屏幕共享已停止");
  }

  // 可选：断开所有连接
  for (const item of pcMap.values()) {
    item.pc.close();
  }
  pcMap.clear();
}

// 进行屏幕共享
async function sendScreen() {
  ws = new WebSocket("ws://localhost:9000");
  ws.onopen = () => {
    ws.send(JSON.stringify({ type: "restart" }));
  };
 
  ws.onmessage = async (msg) => {
    let message = await getMessageData(msg);
    console.log("message", message);
    // 中途加入的接收端
    if (message.type === "link") {
      // 如果连接端已经存在
      if (pcMap.has(message.from)) {
        const item = pcMap.get(message.from);
        item.pc.close();
        item.pc = createNewPc(ws, message.from);    // 创建新的连接
        // 发送offer
        const offer = await item.pc.createOffer();
        await item.pc.setLocalDescription(offer);
        ws.send(
          JSON.stringify({ type: "offer", data: offer, to: message.from })
        );
      } else {
        // 为新的接收端创建 pc
        const item = {
          data: message.data,
          pc: createNewPc(ws, message.from),
        };
        pcMap.set(message.from, item);
        const offer = await item.pc.createOffer();
        await item.pc.setLocalDescription(offer);
        // 发送端 发送offer
        ws.send(
          JSON.stringify({ type: "offer", data: offer, to: message.from })
        );
      }
    } else if (message.type === "answer") {
      if (pcMap.has(message.from)) {
        let item = pcMap.get(message.from);
        await item.pc.setRemoteDescription(
          new RTCSessionDescription(message.data),
          () => {
            console.log("answer triger setRemoteDescription success!");
          },
          () => {
            console.log("answer triger setRemoteDescription fail!");
          }
        );
      }
    } else if (message.type === "candidate") {
      if (pcMap.has(message.from)) {
        await item.pc.addIceCandidate(new RTCIceCandidate(item.data));
      }
    }
  };
}
startButton.addEventListener("click", () => {
  navigator.mediaDevices
    .getDisplayMedia({
      audio: true,
      video: {
        // width: 320,
        // height: 240,
        frameRate: 30,
      },
    })
    .then((stream) => {
      screenStream = stream;
      video.srcObject = stream;
      video.onloadedmetadata = (e) => video.play();
      sendScreen();
    })
    .catch((e) => console.log(e));
});

stopButton.addEventListener("click", () => {
  video.pause();
  stopSharing();
  if (ws) {
    ws.close();
  }
});
